#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

pthread_mutex_t mutex;
double pi;
int doorgaan = 1;
int i;

void* calculatePi(void* argument) {
	int max;
	
	pi = 0;
	max = *((int*)argument);

	for (i = 0; i < max && doorgaan; i++) {
		int g;
		g = pthread_mutex_lock(&mutex);
		// printf("tussenwaarde = %.15f\n", (double)((1-2*(i%2)) / (2*(double)(i)+1)));
		pi += (1-2*(i%2)) / (double)(2*i+1);
		g = pthread_mutex_unlock(&mutex);
	}
	
	if (i < max) {
		printf("Tijd is op!\n");
	} else {
		doorgaan = 0;
	}
	
	return NULL;
}

void* printPi(void* argument) {
	int* printerArgs = (int*)argument;
	int maxtime = printerArgs[0];
	int timestep = printerArgs[1];
	int t;
	
	for (t = 0; t < maxtime && doorgaan; t+=timestep) {
		int g;
		g = pthread_mutex_lock(&mutex);
		// printf("tussenwaarde = %.15f\n", (double)((1-2*(i%2)) / (2*(double)(i)+1)));
		printf("Pi is after %12d i, %8d msec: %.20f\n", i, t/1000, pi*4);
		g = pthread_mutex_unlock(&mutex);
		usleep(timestep);
	}
	
	if (t < maxtime) {
		printf("Klaar!\n");
	} else {
		doorgaan = 0;
	}
	
	return NULL;
}

int main(int argc, char* argv[]) {
	pthread_t calculator;
	pthread_t printer;
	
	int iterations = 1000;
	int maxtime = 10000;
	int timestep = 1000;
	int* printerArgs = malloc(2*sizeof(int));
	if (argc < 3) {
		printf("Geef me wel even 2 argumenten mee aub!\n");
		return 1;
	} else if (argc > 3) {
		timestep = atoi(argv[3]);
	}
	iterations = atoi(argv[1]);
	maxtime = atoi(argv[2]);
	printerArgs[0] = maxtime;
	printerArgs[1] = timestep;
	
	pthread_create(&calculator, NULL, &calculatePi, &iterations);
	pthread_create(&printer, NULL, &printPi, &printerArgs[0]);
	pthread_join(calculator, NULL);
	pthread_join(printer, NULL);
	return 0;
}

